﻿'use strict';
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ejs = require('ejs');
var db = require('./db/db.js');
var config = require('./config.js');

var session = require('express-session')
var SessionStore = require('express-mysql-session')
var jwt = require('jsonwebtoken');
var xml2js = require('xml2js');


var index = require('./routes/index.js')
var api = require('./routes/api.js')
var admin = require("./routes/admin.js");
var callback = require("./routes/callback.js");
var wxapi = require("./routes/wxapi.js");
var log = require("./util/logger");


const schedule = require('node-schedule');

//实例化 express 并赋值app变量
var app = express();

//TOKEN




app.set('views', path.join(__dirname, 'views'));
app.engine('html', ejs.__express);
app.set('view engine', 'html');

//设置图标
//app.use(express.favicon());
app.use(logger('dev'));
app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: false }));

app.use(cookieParser());

app.use(session({
    key: 'session_cookie_name',
    secret: 'session_cookie_secret',
    store: new SessionStore(db.config)
}));


app.use(express.static(path.join(__dirname, 'public')));
app.use("/uploads", express.static(path.join(__dirname, 'uploads')));
app.use("/dist", express.static(path.join(__dirname, 'dist')));

// app.use(function (rq, res, next) {
//     // 定义 不用token 的api
//     //console.log("body" + rq.body.token + rq.query.token + rq.headers);
//     // console.log(rq.headers);
//     if (rq.originalUrl.indexOf('/crm1') >= 0 || rq.originalUrl.indexOf('/wxapi') >= 0) {

//         var token = rq.body.token || rq.query.token || rq.headers["x-access-token"];
//         // console.log("token" + token);
//         jwt.verify(token, config.token.secretOrPrivateKey, function (err, decoded) {
//             if (err) {
//                 // 返回错误信息
//                 res.send({
//                     status: 401,
//                     success: false,
//                     message: 'token效验失败' + err
//                 });
//                 return;
//             } else {
//                 // 解析必要的数据（相应字段为定义token时的字段）
//                 //    console.log(decoded);
//                 // 跳出中间件
//                 return next();
//             }
//         });
//     } else {
//         return next();
//     }


// });


app.use(xmlBodyParser);

function xmlBodyParser(req, res, next) {
    console.log("我是中间件");
    if (req._body) return next();
    req.body = req.body || {};

    // ignore GET
    if ('GET' == req.method || 'HEAD' == req.method) return next();

    // check Content-Type

    if (!req.is("text/xml")) return next();

    // flag as parsed
    req._body = true;

    // parse
    var buf = '';
    req.setEncoding('utf8');
    req.on('data', function (chunk) { buf += chunk });
    req.on('end', function () {
        var parseString = xml2js.parseString;
        parseString(buf, function (err, json) {
            if (err) {
                err.status = 400;
                next(err);
            } else {
                req.body = json;
                next();
            }
        });
    });
};


app.all('*', function (req, res, next) {

    // console.log("req.headers.origin", req.headers.origin);
    // res.header("Access-Control-Allow-Origin", req.headers.origin);
    // res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    // res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    // res.header("Access-Control-Allow-Headers", "Content-Type,Access-Token,x-access-token");
    // res.header("X-Powered-By", ' 3.2.1')
    // if (req.method == "OPTIONS") res.send(200);
    // else next();
    res.header("Access-Control-Allow-Origin", "*");

    res.header("Access-Control-Allow-Credentials", true);

    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,token");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", 'BIM');
    // res.header("Content-Type", "application/json;charset=utf-8");
    next();
});



//匹配任何路由

app.use('/api', api);
app.use('/admin', checkIfAdmin, admin);
app.use('/callback', callback);
app.use('/wxapi', wxapi);

app.use('/', index);


function checkIfAdmin(rq, res, next) {
    //  console.log("rq.headers", rq.headers);
    var token = rq.headers["token"] || rq.headers["authorization"];
    console.log("token" + token);
    jwt.verify(token, config.token.secretOrPrivateKey, function (err, decoded) {
        if (err) {
            // 返回错误信息
            return next();
            res.send({
                status: 401,
                success: false,
                message: 'token效验失败' + err
            });
            return;
        } else {
            // 解析必要的数据（相应字段为定义token时的字段）
            //    console.log(decoded);
            // 跳出中间件
            return next();
        }
    });
}
function checkIfsuper(req, res, next) {
    console.log("tenantid" + req.session.tenantid);
    if (typeof (req.session.tenantid) == "undefined") {
        res.redirect('/login');
    }
    if (req.session.issuper == "1") {
        console.log("super验证通过");
        next();

    } else {
        res.write("no Permission");
        res.end();

    }

}


// catch 404 and forward to error handler
app.use(function (req, res, next) {

    var err = new Error('Not Found');

    err.status = 404;

    next(err);

});

if (app.get('env') === 'development') {

    app.use(function (err, req, res, next) {

        res.status(err.status || 500);

        res.render('error', {

            message: err.message,

            error: err

        });

    });

}


app.use(function (err, req, res, next) {

    res.status(err.status || 500);

    res.render('error', {

        message: err.message,

        error: {}

    });

});


var port = 3031;

var server = app.listen(port, function () {
    console.log('Express server listening on port ' + server.address().port);
});

